"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，结合保存点测试，设置、回滚保存点，提交
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、连接数据库，关闭自动提交，建表并插入数据，设置保存点，再插入1条数据，
       回滚保存点，查询数据，提交事务
    2、新开会话查询表数据
    3、清理环境
Expect      :
    1、建表成功
    2、1条数据
    3、成功
History     :
"""

import os
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0024'
        self.db_name = 'db_autocommit_0024'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:连接数据库，关闭自动提交，建表并插入数据，设置保存点，' \
                '再插入一条数据，回滚保存点，查询数据，提交事务;expect:建表成功-----'
        self.log.info(text1)
        sql = f"set autocommit to off;" \
              f"drop table if exists {self.tb_name};" \
              f"create table {self.tb_name}(c_char char(20));" \
              f"insert into {self.tb_name} values('init');" \
              f"savepoint s1;" \
              f"insert into {self.tb_name} values('save1');" \
              f"select c_char from {self.tb_name} order by 1;" \
              f"rollback to s1;" \
              f"select c_char from {self.tb_name} order by 1;" \
              f"commit;"
        result1 = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(result1)
        self.assertIn('SET', result1, f"关闭自动提交失败: {text1}")
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result1,
                      f"建表失败: {text1}")
        self.assertEqual(result1.count(self.constant.INSERT_SUCCESS_MSG), 2,
                         f"insert失败: {text1}")
        self.assertIn('SAVEPOINT', result1, f"执行失败: {text1}")
        self.assertIn('2 rows', result1, f"执行失败: {text1}")
        self.assertEqual('init', result1.splitlines()[-4].strip(),
                         f"执行失败: {text1}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result1,
                      f"提交失败: {text1}")

        text2 = '-----step2:查询表数据;expect:1条数据-----'
        self.log.info(text2)
        result2 = self.pri_sh.execut_db_sql(
            f"select * from {self.tb_name};", dbname=self.db_name)
        self.log.info(result2)
        self.assertIn('init', result2, f"执行失败: {text1}")

    def tearDown(self):
        text3 = '-----step3:清理环境 expect:成功-----'
        self.log.info(text3)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text3}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
